#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List, Dict, Any, Optional
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query, Path
from fastapi.responses import JSONResponse

from app.core.dependencies import get_services
from app.core.exceptions import NotFoundError, DatabaseError
from app.models.api import (
    ProjectCreate,
    ProjectUpdate,
    ProjectResponse,
    MessageResponse,
    PaginatedResponse
)

# 创建路由
router = APIRouter()


@router.post("", response_model=ProjectResponse)
async def create_project(
    project_data: ProjectCreate,
    services=Depends(get_services)
):
    """创建项目"""
    try:
        project_dict = await services["project_service"].create_project(
            name=project_data.name,
            description=project_data.description
        )
        
        # 直接返回项目字典
        return project_dict
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("", response_model=PaginatedResponse)
async def list_projects(
    limit: int = Query(10, ge=1, le=100),
    offset: int = Query(0, ge=0),
    services=Depends(get_services)
):
    """列出项目"""
    try:
        projects, total = await services["project_service"].list_projects(
            limit=limit,
            offset=offset
        )
        
        # 项目已经是字典格式，直接使用
        return {
            "items": projects,
            "total": total,
            "limit": limit,
            "offset": offset
        }
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{project_id}", response_model=ProjectResponse)
async def get_project(
    project_id: str = Path(..., description="项目ID"),
    services=Depends(get_services)
):
    """获取项目"""
    try:
        project_dict = await services["project_service"].get_project(project_id)
        return project_dict
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/{project_id}", response_model=ProjectResponse)
async def update_project(
    project_data: ProjectUpdate,
    project_id: str = Path(..., description="项目ID"),
    services=Depends(get_services)
):
    """更新项目"""
    try:
        project_dict = await services["project_service"].update_project(
            project_id=project_id,
            name=project_data.name,
            description=project_data.description
        )
        return project_dict
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/{project_id}", response_model=MessageResponse)
async def delete_project(
    project_id: str = Path(..., description="项目ID"),
    services=Depends(get_services)
):
    """删除项目"""
    try:
        await services["project_service"].delete_project(project_id)
        return {"message": f"项目 {project_id} 已删除"}
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))